import { loginFn, getUserInfo } from '@/api/sys'
import md5 from 'md5'
import { setItem, getItem, removeItem } from '@/utils/storage'
import { TOKEN } from '@/constant'
import router, { resetRouter } from '@/router'
import { setTimeStamp } from '@/utils/auth'
export default {
  namespaced: true,
  state: () => ({
    token: getItem(TOKEN) || '',
    userinfo: {}
  }),
  mutations: {
    setToken(state, token) {
      state.token = token
      setItem(TOKEN, token)
    },
    setUserInfo(state, userinfo) {
      state.userinfo = userinfo
    }
  },
  actions: {
    login(contxt, userinfo) {
      const { username, password } = userinfo
      return new Promise((resolve, reject) => {
        loginFn({ username, password: md5(password) })
          .then((data) => {
            this.commit('user/setToken', data.data.data.token)
            setTimeStamp() // 存入登录时间戳
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    async getUserInfo() {
      const res = await getUserInfo()
      debugger
      this.commit('user/setUserInfo', res.data)
      return res
    },
    logout() {
      resetRouter()
      this.commit('user/setToken', '')
      this.commit('user/setUserInfo', {})
      removeItem()
      router.push('/login')
    }
  }
}
